#include "cutimage.h"
#include <QApplication>
#include <QDebug>
#include <QColor>
#include <cmath>
#include <QtMath>
#include <QImage>


CutImage::CutImage(QObject *parent) : QObject(parent)
{
    capturePixMap = new QPixmap;
}

void CutImage::captureNowFullScreen()
{
    QScreen *screen = QApplication::primaryScreen();
    QPixmap screenshot = screen->grabWindow(0);
    screenshot.save(NowImgPath);
}

void CutImage::captureLastFullScreen()
{
    QScreen *screen = QApplication::primaryScreen();
    QPixmap screenshot = screen->grabWindow(0);
    screenshot.save(LastImgPath);
}

double CutImage::calculateImageSimilarity()
{
    QImage image1(NowImgPath);
    if (image1.isNull())
    {
        qDebug() << "无法打开图像文件：" << NowImgPath;
        return 0.0;
    }

    QImage image2(LastImgPath);
    if (image2.isNull())
    {
         qCritical() << "无法打开图像文件：" << LastImgPath;
         return 0.0;
    }

    if (image1.size() != image2.size())
    {
         qWarning() << "图像尺寸不同，无法计算相似度。";
         return 0.0;
    }

    int width = image1.width();
    int height = image1.height();
    int pixelCount = width * height;
    double similarity = 0.0;

    for (int y = 0; y < height; ++y)
    {
        for (int x = 0; x < width; ++x)
        {
            QRgb pixel1 = image1.pixel(x, y);
            QRgb pixel2 = image2.pixel(x, y);

            double diff = qSqrt(qPow(qRed(pixel1) - qRed(pixel2), 2) + qPow(qGreen(pixel1) - qGreen(pixel2), 2) +qPow(qBlue(pixel1) - qBlue(pixel2), 2));
            similarity += (255.0 - diff) / 255.0;
        }
     }
     similarity /= pixelCount;
     qDebug() << similarity;
     return similarity;
}


bool CutImage::compareImages(double tolerance)
{
    double a = calculateImageSimilarity();
    if (a >= tolerance)
        return true;
    else
        return false;
}

void CutImage::captureTextPosition(QVector<int> vec)
{
    int x1=vec[0];
    int y1=vec[1];  // 四个点的坐标
    int x2=vec[2];
    int y2=vec[3];
    int x3=vec[4];
    int y3=vec[5];
    int x4=vec[6];
    int y4=vec[7];
    // 计算矩形框的左上角和右下角坐标
    int left = std::min(std::min(x1, x2), std::min(x3, x4));
    int top = std::min(std::min(y1, y2), std::min(y3, y4));
    int right = std::max(std::max(x1, x2), std::max(x3, x4));
    int bottom = std::max(std::max(y1, y2), std::max(y3, y4));
    QRect rect(left, top, right - left, bottom - top);
    QImage originalImage("/home/mhc/Code/images/now.png");
    QImage croppedImage = originalImage.copy(rect);
    croppedImage.save("/home/mhc/Code/images/test.png");
}

CutImage::~CutImage()
{

}
